package cn.yunhe.controller;

import cn.yunhe.entity.User;
import cn.yunhe.services.IUserService;
import cn.yunhe.services.impl.UserService;
import cn.yunhe.utils.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import lombok.Data;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Pattern;

@Data
public class UserAction extends BaseAction implements ModelDriven {
    private User user = new User();
    private List<User> list;
    IUserService iUserService = new UserService();
    PrintWriter out=null;

    @Override
    public Object getModel() {
        return user;
    }

    public String list() {
        System.out.println("list");
        List<User> ulist = iUserService.userList();
        if (ulist.size() > 0) {
            list = ulist;
            return SUCCESS;
        } else {
            getMapRequest().put("msg", "添加用户失败,请<a href='userList.html'>重试<a/>");
            return "error";
        }
    }

    public String add() {
        System.out.println("add");
        if (user.getUname() != null && !user.getUname().equals("")) {
            User user = new User(getUser().getUname(), getUser().getUpwd());
            int row = iUserService.addUser(user);
            if (row > 0) {
                return SUCCESS;
            } else {
                getMapRequest().put("msg", "添加用户失败,请<a href='userList.html'>重试<a/>");
                return "error";
            }
        } else {
            getMapRequest().put("msg", "用户名或密码不能为空,请<a href='userList.html'>重试<a/>");
            return "error";
        }
    }

    public void validateAdd() throws IOException {
        System.out.println("validateAdd");
        if (user.getUname() == null || "".equals(user.getUname())) {
            addFieldError("uname","用户名不能为空");
        }else if (user.getUpwd() == null || "".equals(user.getUpwd())){
            addFieldError("upwd","密码不能为空");
        }else if (!Pattern.matches("\\w{6,10}", user.getUpwd().trim())){
            addFieldError("upwd", "密码必须由6至10位数字与英文字母组成");
        }
    }

    public String del() {
        int row = iUserService.delUser(user);
        if (row > 0) {
            return null;
        } else {
            getMapRequest().put("msg", "用户删除失败,请<a href='userList.html'>重试<a/>");
            return "error";
        }
    }
}

